package com.wang.see.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wang.see.domain.ImageRepository;
import com.wang.see.domain.MusicRepository;
import com.wang.see.pojo.Image;
import com.wang.see.pojo.Music;
import com.wang.see.utils.FindImgsUtil;

@Controller
public class ImageController {

	@Autowired
	ImageRepository imageRepository;
	
	@Autowired
	MusicRepository musicRep;

	@Value("${find.path}")
	private String path;

	@Value("${page.size}")
	private int size;

	@Value("${nginx.addr}")
	private String nginxAddr;

	@RequestMapping("/save")
	public String saveImages() {
		imageRepository.save(new FindImgsUtil(path).getImgs());
		return "hello springboot";
	}

	@RequestMapping("/")
	public String selectImages(ModelMap model, HttpServletRequest request) {
		String pageStr = request.getParameter("page");
		if (StringUtils.isEmpty(pageStr))
			pageStr = "1";

		int page;
		try {
			page = Integer.parseInt(pageStr);
			if (page < 1)
				page = 1;
		} catch (Exception e) {
			page = 1;
		}

		List<Image> list = imageRepository.getImgFolder((page - 1) * size, size);
		if (list.size() > 0)
			model.addAttribute("imgFolderList", list);
		
		List<Music> musicList=musicRep.getMusicList();
		if(musicList.size()>0){
			model.addAttribute("musicList", musicList);
		}

		int countPage = imageRepository.getAllImgFolder().size();
		model.addAttribute("page", page);
		model.addAttribute("countPage", countPage % size == 0 ? countPage / size : countPage / size + 1);
		model.addAttribute("nginxAddr", nginxAddr);
		return "index";
	}

	@RequestMapping("/showImg")
	public String show(ModelMap model, @RequestParam("imgFolder") String imgFolder) {
		if (StringUtils.isEmpty(imgFolder))
			return "error";
		List<Image> imgsList = imageRepository.findByImgFolderName(imgFolder);
		if (imgsList.size() < 1)
			return "error";
		model.addAttribute("imgsList", imgsList);
		model.addAttribute("nginxAddr", nginxAddr);

		return "show";
	}
}
